<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import api from "@/api/api.js"
// 对话部分
const inputMessage = ref('');
const message_list = ref([]);
const lastMessageLength = ref(0);//用于轮询检查是否有新消息
const sendMessage = async () => {
  if (inputMessage.value.trim() === '') return;
  await api.postContent({ content: inputMessage.value })

  inputMessage.value = '';

};

const chatStartTime = ref('');
// 页面加载时设置当前时间


// 加载状态
const loading = ref(false);
const finished = ref(false);
const onLoad = async () => {
  loading.value = true;//开始加载
  await get_MessageList().then(res => {
    loading.value = false;//获取到数据后结束加载
  })

};

// 获取消息列表
const get_MessageList = async () => {
  await api.getMessageList().then(res => {
    if (res.length > lastMessageLength.value) {
      message_list.value = res;
      lastMessageLength.value = res.length;
    }
  });
};

let pollInterval = null;
onMounted(async () => {
  const now = new Date();
  const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };
  chatStartTime.value = now.toLocaleDateString('zh-CN', options);

  // 初始化消息列表
  await get_MessageList();
  lastMessageLength.value = message_list.value.length;

  // 开始轮询
  pollInterval = setInterval(async () => {
    await get_MessageList();
  }, 10000);
});


onUnmounted(() => {
  clearInterval(pollInterval);
})
</script>

<template>
  <div class="contact-container">
    <main>
      <div class="chat-start-time" v-if="chatStartTime">
        {{ chatStartTime }}
      </div>
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" offset="100px">
        <div v-for="(msg, index) in message_list" :key="index" class="message-item">
          <!-- 用户消息 -->
          <div v-if="msg.adminId === 0" class="user-message">
            <div>
              <p class="user">我</p>
              <p class="content">{{ msg.content }}</p>
            </div>
            <img src="@/assets/icons/avatar.png" alt="">
          </div>
          <!-- 客服消息 -->
          <div v-else class="admin-message">
            <img src="@/assets/icons/avatar.png" alt="">
            <div>
              <p class="admin">客服</p>
              <p class="content">{{ msg.content }}</p>
            </div>

          </div>
        </div>
      </van-list>

    </main>
    <footer class="input-container">
      <van-field v-model="inputMessage" left-icon="search" placeholder="请输入您想咨询的内容" @keyup.enter="sendMessage"
        style="width: 100%" />
      <van-button class="button" type="primary" @click="sendMessage">发送</van-button>
    </footer>
  </div>
</template>


<style lang="less" scoped>
@import url("@/styles/my/contact");
</style>
